from django.conf.global_settings import MEDIA_URL
from django.contrib.auth import authenticate, login,logout as out
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.http import JsonResponse
import os

from Login_regist.forms import UserLRForm
from Login_regist.models import UserDetails
from learning_learning.settings import MEDIA_URL
from resources.models import Classes


class LoginView(View):
    def get(self, request):
        form = UserLRForm()
        return render(request, 'templates/LR/Login.html', {'form':form})

    def post(self, request):
        #接收表单对象 接收数据保存到Form表单对象中
        form = UserLRForm(request.POST)
        #判断用户提交的数据格式是否合法
        if form.is_valid():
            #从表单中获取通过校验后的数据
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            #查询数据库，对比账号密码是否正确
            user = authenticate(username=username, password=password)

            if user:
                #用auth系统中的login()函数来保存用户登录状态 维持状态
                login(request, user)
                #获取next后面的地址 GET得到用户传来的请求消息.get获取键为next的值即为地址
                next_url = request.GET.get('next')
                #判断是否有请求参数值
                if next_url:
                    return redirect(next_url)
                return redirect('index')

            else:
                #用户名或密码不正确返回错误消息
                form.add_error(None,"用户名或密码不正确！")

        return render(request, 'templates/LR/Login.html', {'form':form})


class RegisterView(View):
    def get(self, request):
        form = UserLRForm()
        return render(request, 'templates/LR/regist.html', {'form':form})

    def post(self, request):
        #创建一个表单对象并且绑定用户输入的数据
        form = UserLRForm(request.POST)
        #获取数据
        #request.POST保存的是数据字典.get方法通过键获取值
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            #传入数据到数据库
            user = User(username=username)
            #密码加密
            user.set_password(password)
            userdetail = UserDetails(user=user)
            try:
                user.save()
            except IntegrityError:
                message = '用户名已存在，请重写输入'
            else:
                userdetail.save()
                message = '注册成功'

            return render(request, 'templates/LR/regist.html', {'form':form, 'message':message})


def logout(request,**kwargs):
    out(request)
    return redirect('login')


def index(request,**kwargs):
    print(Classes.objects.all())
    sort = '书籍'
    classes = '考研数学一'
    res = Classes.objects.get(name=classes)
    print(1)
    resources = res.book_classes.all()
    print(2)
    print(resources)
    user = User.objects.get(username=request.user)
    print(type(user))
    userdetails = UserDetails.objects.get(user=user)
    print(userdetails.cover)
    return HttpResponse(render(request,
                               'templates/LR/index.html',
                               context={
                                   'username':request.user.username,
                                   'sort':['课程','书籍','博客'],
                                   'classes': Classes.objects.all(),
                                   'resources':resources,
                                   'user':userdetails,
                               }
                               ))

def not_find(request,**kwargs):
    return HttpResponse('哥么儿走错了')

def user_center(request,**kwargs):
    user = User.objects.get(username=request.user)
    userdetails = UserDetails.objects.get(user=user)

    return HttpResponse(render(request,
                               'templates/LR/user_center.html',
                               context={
                                   'username': request.user.username,
                                   'user':userdetails,
                               }
                               ))

def upload_avatar(request,**kwargs):
    if request.method == "POST" and request.FILES.get("avatar"):
        avatar = request.FILES["avatar"]
        user = User.objects.get(username=request.user)
        user_details = UserDetails.objects.get(user=user)

        # 1️定义存储路径 (存放到 MEDIA_ROOT)
        avatar_filename = f"user_{request.user.id}_{avatar.name}"
        avatar_path = os.path.join(MEDIA_URL, avatar_filename)
        print(avatar_path)

        # 2️删除旧头像 (避免占用空间)
        if user_details.cover and user_details.cover != "static/media/index.png":
            old_path = os.path.join(MEDIA_URL, user_details.cover.strip("/"))
            print(old_path)
            if os.path.exists(old_path):
                os.remove(old_path)

        # 3️保存新头像
        with open(avatar_path, "wb") as destination:
            for chunk in avatar.chunks():
                destination.write(chunk)

        # 4️更新数据库 (存储相对路径)
        user_details.cover = avatar_filename
        user_details.save()

        return JsonResponse({
            "status": "success",
            "avatar_url": "/static/media/" + user_details.cover
        })

    return JsonResponse({"status": "error", "message": "无效请求"})

@csrf_exempt
def set_goal(request):
    if request.method == "POST":
        data = json.loads(request.body)
        user = User.objects.get(username=request.user)
        user_details = UserDetails.objects.get(user=user)

        user_details.target_start_date = data.get("target-start")
        user_details.target_end_date = data.get("target-end")
        user_details.target = data.get("target-content")
        user_details.save()

        return JsonResponse({
            "status": "success",
            "target_start_date": user_details.target_start_date,
            "target_end_date": user_details.target_end_date,
            "target": user_details.target
        })

    return JsonResponse({"status": "error", "message": "无效请求"})

@csrf_exempt
def set_plan(request):
    if request.method == "POST":
        data = json.loads(request.body)
        user = User.objects.get(username=request.user)
        user_details = UserDetails.objects.get(user=user)

        user_details.plan = data.get("plan-content")
        user_details.save()

        return JsonResponse({
            "status": "success",
            "plan": user_details.plan
        })

    return JsonResponse({"status": "error", "message": "无效请求"})


